package com.nifostasky.comic.exceptions;

import com.nifostasky.comic.vos.JsonResult;
import com.nifostasky.comic.vos.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全球异常
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 只捕获 BusinessException 异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    private JsonResult myExceptionHandler(BusinessException e) {
        //自定义异常状态信息
        return  new JsonResult(e.getCode(),e.getMsg());
    }

    /**
     * 捕获 HttpMessageNotReadableException异常,
     * 前端传递的json数据格式错误
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    private JsonResult httpMessageNotReadableHandler(HttpMessageNotReadableException e){
        //提示json格式错误
        return  new JsonResult(ResultCode.JSON_PARSE_ERROR);
    }

    /**
     * 默认异常处理,处理其他未专门处理的所有异常
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    JsonResult exceptionHandler(Exception exception) {
        log.error("{}",exception);
        //统一处理异常,返回规定的json格式
        return new JsonResult(ResultCode.SYSTEM_SERVER_ERROR);
    }

}
